import 'dart:async';
import '../models/account.dart';
import '../models/show.dart';
import '../models/platform_config.dart';
import '../providers/ticket_hunter_provider.dart';
import '../utils/logger.dart';
import 'ticket_hunter_service.dart';
import 'maoyan_ticket_service.dart';

/// 统一抢票服务
/// 根据平台类型调用相应的抢票服务
class UnifiedTicketService {
  final TicketHunterService _damaiService = TicketHunterService();
  final MaoyanTicketService _maoyanService = MaoyanTicketService();

  /// 提交订单
  Future<HuntingResult> submitOrder({
    required Account account,
    required Show show,
    required TicketSku sku,
    required Map<String, dynamic> params,
  }) async {
    AppLogger.info('Unified service submitting order for platform: ${show.platform}');
    
    switch (show.platform) {
      case TicketPlatform.damai:
        // 转换Show为Concert（向后兼容）
        final concert = _convertShowToConcert(show);
        return await _damaiService.submitOrder(
          account: account,
          concert: concert,
          sku: sku,
          params: params,
        );
        
      case TicketPlatform.maoyan:
        return await _maoyanService.submitOrder(
          account: account,
          show: show,
          sku: sku,
          params: params,
        );
    }
  }

  /// 搜索演出/电影
  Future<List<Map<String, dynamic>>> search({
    required TicketPlatform platform,
    required String keyword,
    Map<String, dynamic>? filters,
  }) async {
    AppLogger.info('Searching on platform: $platform, keyword: $keyword');
    
    switch (platform) {
      case TicketPlatform.damai:
        // 调用大麦搜索API（需要在TicketHunterService中添加）
        return await _searchDamai(keyword, filters);
        
      case TicketPlatform.maoyan:
        return await _maoyanService.searchMovies(keyword);
    }
  }

  /// 获取详情
  Future<Map<String, dynamic>?> getDetail({
    required TicketPlatform platform,
    required String itemId,
  }) async {
    switch (platform) {
      case TicketPlatform.damai:
        return await _damaiService.getItemDetail(itemId);
        
      case TicketPlatform.maoyan:
        return await _maoyanService._getMovieDetail(itemId);
    }
  }

  /// 批量抢票
  Future<List<HuntingResult>> batchSubmitOrders({
    required List<Account> accounts,
    required Show show,
    required TicketSku sku,
    required Map<String, dynamic> params,
  }) async {
    final results = <HuntingResult>[];
    final futures = <Future<HuntingResult>>[];

    // 并发提交订单
    for (final account in accounts) {
      final future = submitOrder(
        account: account,
        show: show,
        sku: sku,
        params: params,
      );
      futures.add(future);
    }

    // 等待所有结果
    final allResults = await Future.wait(futures);
    results.addAll(allResults);

    return results;
  }

  /// 智能抢票策略
  Future<HuntingResult> smartHunting({
    required List<Account> accounts,
    required Show show,
    required List<TicketSku> skus,
    required Map<String, dynamic> params,
  }) async {
    AppLogger.info('Starting smart hunting for show: ${show.name}');
    
    // 按优先级排序SKU
    final sortedSkus = List<TicketSku>.from(skus);
    sortedSkus.sort((a, b) => b.priority.index.compareTo(a.priority.index));

    // 为每个SKU尝试抢票
    for (final sku in sortedSkus) {
      if (!sku.isEnabled) continue;

      AppLogger.info('Trying SKU: ${sku.name} with ${accounts.length} accounts');

      // 使用所有账号并发抢票
      final results = await batchSubmitOrders(
        accounts: accounts,
        show: show,
        sku: sku,
        params: params,
      );

      // 检查是否有成功的结果
      final successResults = results.where((r) => r.success).toList();
      if (successResults.isNotEmpty) {
        AppLogger.info('Smart hunting succeeded with SKU: ${sku.name}');
        return successResults.first;
      }

      // 检查是否被风控
      final blockedResults = results.where((r) => r.isBlocked).toList();
      if (blockedResults.length > accounts.length * 0.5) {
        AppLogger.warning('Too many accounts blocked, stopping smart hunting');
        return HuntingResult(
          success: false,
          message: '账号风控率过高，停止抢票',
          timestamp: DateTime.now(),
          isBlocked: true,
        );
      }

      // 短暂延迟后尝试下一个SKU
      await Future.delayed(Duration(milliseconds: params['skuRetryDelay'] ?? 500));
    }

    return HuntingResult(
      success: false,
      message: '所有SKU抢票失败',
      timestamp: DateTime.now(),
    );
  }

  /// 转换Show为Concert（向后兼容）
  Concert _convertShowToConcert(Show show) {
    return Concert(
      id: show.id,
      name: show.name,
      artist: show.artist ?? '',
      venue: show.venue,
      showTime: show.showTime,
      saleStartTime: show.saleStartTime,
      itemId: show.itemId,
      skus: show.skus,
      status: _convertShowStatus(show.status),
      maxConcurrency: show.maxConcurrency,
      retryCount: show.retryCount,
      retryDelay: show.retryDelay,
      autoStart: show.autoStart,
      description: show.description,
      posterUrl: show.posterUrl,
      metadata: show.metadata,
      createdAt: show.createdAt,
      updatedAt: show.updatedAt,
    );
  }

  /// 转换状态枚举
  ConcertStatus _convertShowStatus(ShowStatus status) {
    switch (status) {
      case ShowStatus.pending:
        return ConcertStatus.pending;
      case ShowStatus.active:
        return ConcertStatus.active;
      case ShowStatus.completed:
        return ConcertStatus.completed;
      case ShowStatus.cancelled:
        return ConcertStatus.cancelled;
    }
  }

  /// 大麦搜索（需要实现）
  Future<List<Map<String, dynamic>>> _searchDamai(
    String keyword,
    Map<String, dynamic>? filters,
  ) async {
    // TODO: 实现大麦搜索功能
    AppLogger.warning('Damai search not implemented yet');
    return [];
  }

  /// 获取平台配置
  PlatformConfig getPlatformConfig(TicketPlatform platform) {
    return PlatformConfig.getConfig(platform);
  }

  /// 检查平台可用性
  Future<bool> isPlatformAvailable(TicketPlatform platform) async {
    try {
      final config = getPlatformConfig(platform);
      // 简单的健康检查
      // TODO: 实现更完善的可用性检查
      return config.isEnabled;
    } catch (e) {
      AppLogger.error('Check platform availability failed', e);
      return false;
    }
  }
}

// 为了向后兼容，重新导入Concert相关类
import '../models/concert.dart';